package com.ssm.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;

public class MD5andKL {
	public static String Md5(String sourceStr) { 
		  String  result = "";
		  try { 
		   MessageDigest md = MessageDigest.getInstance("MD5"); 
		   md.update(sourceStr.getBytes()); 
		   byte b[] = md.digest(); 
		   int i; StringBuffer buf = new StringBuffer(""); 
		   for (int offset = 0; offset < b.length; offset++) { 
		    i = b[offset]; 
		    if(i<0) 
		     i+= 256; 
		    if(i<16) 
		     buf.append("0"); 
		     buf.append(Integer.toHexString(i)); 
		   } 
		   result = buf.toString();
		  // System.out.println("result: " + result);//32位的加密 
		//   System.out.println("result: " + buf.toString().substring(8,24));//16位的加密 
		  } catch (NoSuchAlgorithmException e) { 
		   // TODO Auto-generated catch block e.printStackTrace(); 
		  } 
		  return result;
		 }
	 // 可逆的加密算法
	 public static String KL(String inStr) {
	  // String s = new String(inStr);
	  char[] a = inStr.toCharArray();
	  for (int i = 0; i < a.length; i++) {
	   a[i] = (char) (a[i] ^ 't');
	  }
	  String s = new String(a);
	  return s;
	 }

	 // 加密后解密
	 public static String JM(String inStr) {
	  char[] a = inStr.toCharArray();
	  for (int i = 0; i < a.length; i++) {
	   a[i] = (char) (a[i] ^ 't');
	  }
	  String k = new String(a);
	  return k;
	 }
	 
	 public static void fun(){
		   // 随机盐对象  
		  
		 String algorithmName = "MD5"; // 加密方式  
		    
		 int hashIterations = 2048; // 加密次数   
         SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator(); 
         // 根据用户名以及随机生成的盐来拼接成密码盐  
         String salt = "shiro" + secureRandomNumberGenerator.nextBytes().toHex();  
         System.out.println(salt);
         // 获取加密后的密码  
         String passWords = new SimpleHash(algorithmName, "123456", salt, hashIterations).toHex();  
         System.out.println(passWords);
	 }
	 
	 // 测试主函数
	 public static void main(String args[]) {
	 String  s=DateUtil.date2String(new Date(), "yyyyMMdd");
	  System.out.println("原始：" + s);
	  System.out.println("MD5后：" + Md5(s));
	  System.out.println("MD5后再加密：" + KL(Md5(s)));
	  System.out.println("解密为MD5后的：" + JM(KL(Md5(s))));
	  fun();
	 }


}
